package com.ruoyi.web.controller.system;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.pagehelper.PageInfo;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.WrapperUtil;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.domain.Product;
import com.ruoyi.system.domain.ProductCategory;
import com.ruoyi.system.domain.vo.AdminPaymentRecordQueryListRes;
import com.ruoyi.system.domain.vo.ProductVo;
import com.ruoyi.system.service.IProductService;
import com.ruoyi.web.service.IProductCategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 商品Controller
 *
 * @author ruoyi
 * @date 2022-05-03
 */
@RestController
@RequestMapping("/system/product")
public class ProductController extends BaseController {
    @Autowired
    private IProductService productService;

    @Autowired
    private IProductCategoryService productCategoryService;

    /**
     * 查询商品列表
     */
//    @PreAuthorize("@ss.hasPermi('system:product:list')")
    @GetMapping("/list")
    public TableDataInfo list(Product product,
                              @RequestParam(name = "pageNum", defaultValue = "1") Integer pageNum,
                              @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {
        Page<Product> productPage = productService.page(new Page<>(pageNum, pageSize), WrapperUtil.entityWrapper(product));
        List<Product> list = productPage.getRecords();
        List<Long> categoryIds = list.stream().map(Product::getCategoryId).collect(Collectors.toList());
        List<ProductVo> productVos = BeanUtil.copyToList(list, ProductVo.class);

        List<ProductCategory> productCategories = productCategoryService.selectProductCategoryById(categoryIds);
        Map<Long, ProductCategory> categoryMap = productCategories.stream()
                .collect(Collectors.toMap(ProductCategory::getId, ProductCategory -> ProductCategory));

        productVos.forEach(p -> {
            ProductCategory category = categoryMap.get(p.getCategoryId());
            if(Objects.nonNull(category)){
                p.setCategoryName(category.getCategoryName());
            }
        });
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(HttpStatus.SUCCESS);
        rspData.setMsg("查询成功");
        rspData.setRows(list);
        rspData.setTotal(productPage.getTotal());
        return rspData;
    }

    /**
     * 导出商品列表
     */
    @PreAuthorize("@ss.hasPermi('system:product:export')")
    @Log(title = "商品", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(Product product) {
        List<Product> list = productService.selectProductList(product);
        ExcelUtil<Product> util = new ExcelUtil<Product>(Product.class);
        return util.exportExcel(list, "商品数据");
    }

    /**
     * 获取商品详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:product:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") String id) {
        return AjaxResult.success(productService.selectProductById(id));
    }

    /**
     * 新增商品
     */
    @PreAuthorize("@ss.hasPermi('system:product:add')")
    @Log(title = "商品", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Product product) {
        return toAjax(productService.insertProduct(product));
    }

    /**
     * 修改商品
     */
    @PreAuthorize("@ss.hasPermi('system:product:edit')")
    @Log(title = "商品", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Product product) {
        return toAjax(productService.updateProduct(product));
    }
    @DeleteMapping("/del")
    public AjaxResult del(@RequestBody Product product) {
        return toAjax(productService.delete(product));
    }
    /**
     * 删除商品
     */
    @PreAuthorize("@ss.hasPermi('system:product:remove')")
    @Log(title = "商品", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable String[] ids) {
        return toAjax(productService.deleteProductByIds(ids));
    }
}
